package cn.suimg.bilibili;

import cn.suimg.bilibili.bean.Option;
import cn.suimg.bilibili.service.WithReplyConsumerImpl;
import cn.suimg.bilibili.util.BiliBiliUtil;
import cn.suimg.bilibili.util.Cookie;
import com.alibaba.fastjson.JSON;
import org.java_websocket.WebSocket;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.FileCopyUtils;

import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.Map;

public class BiliBiliBarrageClient {

    /**
     * Socket URL
     */
    public static final String WEBSOCKET_URL = "wss://broadcastlv.chat.bilibili.com:2245/sub";

    /**
     * cookie缓存文件地址
     */
    public static final String COOKIE_SAVE_PATH = System.getProperty("java.io.tmpdir") + "bilibili.cookie";

    /**
     * Logger
     */
    private static final Logger logger = LoggerFactory.getLogger(BiliBiliBarrageClient.class);

    private static boolean authed;

    public static void main(String[] args) throws URISyntaxException, IOException {


        System.out.println("欢迎使用bilibili直播工具\n本工具完全开源免费\n开源地址:https://gitee.com/Suimg/BiliBili-Barrage-Helper/");
        System.out.println("首先需要进行扫码登录B站。");
        File file = new File(COOKIE_SAVE_PATH);
        Cookie cookie;
        if(!file.exists()){
            logger.info("正在获取登录令牌");
            String oauthKey = BiliBiliUtil.getOauthKey();
            logger.info("正在打开登录窗口");
            BiliBiliUtil.openLoginUrl(oauthKey);
            logger.info("正在等待用户");
             cookie = BiliBiliUtil.waitForLogin(oauthKey);
            if(cookie == null) {
                System.exit(0);
            }
            FileCopyUtils.copy(cookie.toString().getBytes(),file);
        }else{
            logger.info("检测到本地cookie。跳过扫码步骤");
            cookie = new Cookie(new String(FileCopyUtils.copyToByteArray(file)));
        }



        logger.info("正在获取用户信息");
        BiliBiliUtil.getUserInfo(cookie);
        int roomId = BiliBiliUtil.getUserRoomId(Integer.parseInt(cookie.getValue("DedeUserID")));


        SocketClient client = new SocketClient(WEBSOCKET_URL);

        client.setConsumer(new WithReplyConsumerImpl(roomId,cookie));
        logger.info("正在连接到直播间。。。");
        client.connect();

        while (true){
            WebSocket.READYSTATE readyState = client.getReadyState();
            if(readyState.equals(WebSocket.READYSTATE.OPEN)){
                if(!authed){
                    Map<String,Object> authPackage = new HashMap<String, Object>(){{
                        put("uid",0);
                        put("roomid",roomId);
                        put("protover",1);
                        put("platform","web");
                        put("clientver","1.4.0");
                    }};
                    logger.info(JSON.toJSONString(authPackage));
                    client.send(Option.AUTH, JSON.toJSONString(authPackage));
                    client.send(Option.HEARTBEAT,"{}");
                    client.send(Option.HEARTBEAT,"{}");
                    //30秒发送一次心跳包
                    new Thread(()->{
                        while (true){
                            try {
                                Thread.sleep(30000);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                            client.send(Option.HEARTBEAT,"{}");
                        }
                    }).start();
                    authed=true;
                }

            }
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            if(client.isClosed()){
                break;
            }
        }

    }
}
